<template>
  <div class="ad-management">
    <div class="page-header">
      <h2>广告管理</h2>
      <p>管理网站广告位和广告内容</p>
    </div>
    
    <div class="content-wrapper">
      <!-- 搜索和操作栏 -->
      <div class="search-action-bar">
        <div class="search-box">
          <input 
            type="text" 
            placeholder="搜索广告标题..." 
            v-model="searchQuery"
            @keyup.enter="searchAds"
            class="search-input"
          >
          <button class="search-btn" @click="searchAds">🔍</button>
        </div>
        
        <button class="btn btn-primary create-btn" @click="showAddModal = true">
          <i class="icon">➕</i>
          创建广告
        </button>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>正在加载广告数据...</p>
      </div>
      
      <!-- 空状态 -->
      <div v-else-if="advertisements.length === 0" class="empty-state">
        <div class="empty-icon">📢</div>
        <h3>暂无广告数据</h3>
        <p>{{ searchQuery ? '没有找到匹配的广告' : '还没有创建任何广告' }}</p>
        <button class="btn btn-primary" @click="showAddModal = true" v-if="!searchQuery">
          创建第一个广告
        </button>
      </div>
      
      <!-- 广告列表 -->
      <div v-else class="ads-grid">
        <div 
          class="ad-card" 
          v-for="ad in advertisements" 
          :key="ad.id"
        >
          <div class="card-header">
            <div class="ad-preview">
              <img :src="getImageUrl(ad.imageUrl)" :alt="ad.title" v-if="ad.imageUrl" class="ad-image">
              <div class="ad-placeholder" v-else>
                <span>{{ ad.title ? ad.title.charAt(0) : '广' }}</span>
              </div>
            </div>
            
            <div class="ad-info">
              <h3 class="ad-title">{{ ad.title }}</h3>
              <div class="ad-meta">
                <span class="ad-position">位置: {{ getPositionText(ad.position) }}</span>
                <span class="ad-status" :class="ad.status === 1 ? 'status-active' : 'status-inactive'">
                  {{ ad.status === 1 ? '启用' : '禁用' }}
                </span>
              </div>
            </div>
            
            <div class="card-actions">
              <button class="action-btn edit" @click="editAd(ad)" title="编辑">✏️</button>
              <button class="action-btn delete" @click="deleteAd(ad.id)" title="删除">🗑️</button>
            </div>
          </div>
          
          <div class="card-content">
            <div class="ad-details">
              <div class="detail-row">
                <span class="label">广告ID:</span>
                <span class="value">{{ ad.id }}</span>
              </div>
              <div class="detail-row" v-if="ad.targetUrl">
                <span class="label">目标链接:</span>
                <a :href="ad.targetUrl" target="_blank" class="value link">{{ ad.targetUrl }}</a>
              </div>
              <div class="detail-row" v-if="ad.createdAt">
                <span class="label">创建时间:</span>
                <span class="value">{{ formatDate(ad.createdAt) }}</span>
              </div>
              <div class="detail-row" v-if="ad.updatedAt">
                <span class="label">更新时间:</span>
                <span class="value">{{ formatDate(ad.updatedAt) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页组件 -->
      <div v-if="advertisements.length > 0" class="pagination-wrapper">
        <div class="pagination-info">
          显示第 {{ (pagination.pageNum - 1) * pagination.pageSize + 1 }} - 
          {{ Math.min(pagination.pageNum * pagination.pageSize, pagination.total) }} 条，
          共 {{ pagination.total }} 条记录
        </div>
        
        <div class="pagination-controls">
          <button 
            class="pagination-btn" 
            @click="changePage(pagination.pageNum - 1)"
            :disabled="pagination.pageNum <= 1"
          >
            上一页
          </button>
          
          <div class="page-numbers">
            <button 
              v-for="page in getPageNumbers()" 
              :key="page"
              class="page-number"
              :class="{ active: page === pagination.pageNum }"
              @click="changePage(page)"
            >
              {{ page }}
            </button>
          </div>
          
          <button 
            class="pagination-btn" 
            @click="changePage(pagination.pageNum + 1)"
            :disabled="pagination.pageNum >= Math.ceil(pagination.total / pagination.pageSize)"
          >
            下一页
          </button>
        </div>
      </div>
      
      <!-- 添加/编辑模态框 -->
      <div class="modal-overlay" v-if="showAddModal || showEditModal" @click="closeModal">
        <div class="modal-content" @click.stop>
          <div class="modal-header">
            <h3>{{ showEditModal ? '编辑广告' : '创建广告' }}</h3>
            <button class="close-btn" @click="closeModal">✕</button>
          </div>
          
          <div class="modal-body">
            <form @submit.prevent="saveAd">
              <div class="form-group">
                <label>广告标题 *</label>
                <input type="text" v-model="formData.title" required class="form-input">
              </div>
              
              <div class="form-group">
                <label>广告图片 *</label>
                <div class="image-upload-container">
                  <!-- 图片预览区域 -->
                  <div class="image-preview" v-if="imageUrlForPreview">
                    <img :src="imageUrlForPreview" alt="广告图片预览" class="preview-image">
                    <div class="image-overlay">
                      <button type="button" class="btn-remove" @click="removeImage" title="删除图片">🗑️</button>
                    </div>
                  </div>
                  
                  <!-- 上传区域 -->
                  <div class="upload-area" v-else @click="triggerFileInput" @dragover.prevent @drop.prevent="handleDrop">
                    <input 
                      type="file" 
                      ref="fileInput" 
                      @change="handleFileSelect" 
                      accept="image/*" 
                      style="display: none;"
                    >
                    <div class="upload-content">
                      <div class="upload-icon">📷</div>
                      <p>点击上传或拖拽图片到此处</p>
                      <p class="upload-hint">支持 JPG、PNG、GIF 格式，建议尺寸 800x400px</p>
                    </div>
                  </div>
                  
                  <!-- 上传进度 -->
                  <div class="upload-progress" v-if="uploadProgress > 0 && uploadProgress < 100">
                    <div class="progress-bar">
                      <div class="progress-fill" :style="{ width: uploadProgress + '%' }"></div>
                    </div>
                    <span class="progress-text">{{ uploadProgress }}%</span>
                  </div>
                  
                  <!-- 手动输入链接选项 -->
                  <div class="manual-input-toggle">
                    <button type="button" class="btn-link" @click="showManualInput = !showManualInput">
                      {{ showManualInput ? '使用文件上传' : '手动输入图片链接' }}
                    </button>
                  </div>
                  
                  <!-- 手动输入框 -->
                  <div class="manual-input" v-if="showManualInput">
                    <input 
                      type="url" 
                      v-model="formData.imageUrl" 
                      placeholder="请输入图片链接" 
                      class="form-input"
                    >
                  </div>
                </div>
              </div>
              
              <div class="form-group">
                <label>目标链接 *</label>
                <input type="url" v-model="formData.targetUrl" required class="form-input">
              </div>
              
              <div class="form-row">
                <div class="form-group">
                  <label>广告位置 *</label>
                  <select v-model="formData.position" required class="form-select">
                    <option value="">请选择位置</option>
                    <option value="banner">横幅广告</option>
                    <option value="sidebar">侧边栏</option>
                    <option value="popup">弹窗广告</option>
                    <option value="footer">页脚广告</option>
                  </select>
                </div>
                
                <div class="form-group">
                  <label>状态</label>
                  <select v-model="formData.status" class="form-select">
                    <option value="active">投放中</option>
                    <option value="paused">暂停</option>
                    <option value="draft">草稿</option>
                  </select>
                </div>
              </div>
              
              <div class="form-row">
                <div class="form-group">
                  <label>开始时间 *</label>
                  <input type="datetime-local" v-model="formData.startDate" required class="form-input">
                </div>
                
                <div class="form-group">
                  <label>结束时间 *</label>
                  <input type="datetime-local" v-model="formData.endDate" required class="form-input">
                </div>
              </div>
              
              <div class="form-group">
                <label>广告预览</label>
                <div class="ad-preview-container" v-if="imageUrlForPreview">
                  <img :src="imageUrlForPreview" alt="广告预览" class="preview-image">
                </div>
                <div class="preview-placeholder" v-else>
                  <span>请上传图片或输入图片链接查看预览</span>
                </div>
              </div>
              
              <div class="form-actions">
                <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
                <button type="submit" class="btn btn-primary">{{ showEditModal ? '更新' : '创建' }}</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'AdManagement',
  data() {
    return {
      searchQuery: '',
      showAddModal: false,
      showEditModal: false,
      editingId: null,
      loading: false,
      advertisements: [],
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      formData: {
        title: '',
        imageUrl: '',
        targetUrl: '',
        position: '',
        status: 'active',
        startDate: '',
        endDate: ''
      },
      // 图片上传相关
      uploadProgress: 0,
      showManualInput: false,
      // 后端基础URL
      backendBaseUrl: 'http://localhost:8083',
      // 用于预览的完整图片URL
      imageUrlForPreview: ''
    };
  },
  mounted() {
    this.fetchAdvertisements();
  },
  watch: {
    // 监听手动输入的图片URL变化
    'formData.imageUrl'(newVal) {
      if (newVal) {
        // 如果是完整的URL（以http开头）
        if (newVal.startsWith('http')) {
          this.imageUrlForPreview = newVal;
        } else {
          // 如果是相对路径，拼接后端基础URL
          this.imageUrlForPreview = this.backendBaseUrl + (newVal.startsWith('/') ? newVal : '/' + newVal);
        }
      } else {
        // 如果URL为空，清空预览
        this.imageUrlForPreview = '';
      }
    }
  },
  methods: {
    // 获取广告列表
    async fetchAdvertisements() {
      try {
        this.loading = true;
        const params = {
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize
        };
        
        // 添加搜索关键词
        if (this.searchQuery.trim()) {
          params.keyword = this.searchQuery.trim();
        }
        
        const response = await axios.get('http://localhost:8083/api/v1/advertisements/list', {
          params: params
        });
        
        console.log('获取广告列表响应:', response.data);
        
        if (response.data.code === 200 && response.data.ok) {
          const pageInfo = response.data.data;
          this.advertisements = pageInfo.list || [];
          
          // 更新分页信息
          this.pagination = {
            pageNum: pageInfo.pageNum,
            pageSize: pageInfo.pageSize,
            total: pageInfo.total
          };
        } else {
          console.error('获取广告列表失败:', response.data.msg);
          alert('获取广告列表失败: ' + (response.data.msg || '未知错误'));
        }
      } catch (error) {
        console.error('获取广告列表出错:', error);
        if (error.response) {
          alert('获取广告列表失败: ' + (error.response.data.msg || '服务器错误'));
        } else if (error.request) {
          alert('获取广告列表失败: 网络连接错误');
        } else {
          alert('获取广告列表失败: 请求配置错误');
        }
      } finally {
        this.loading = false;
      }
    },
    
    // 搜索广告
    searchAds() {
      this.pagination.pageNum = 1; // 重置到第一页
      this.fetchAdvertisements();
    },
    
    // 分页相关方法
    changePage(page) {
      if (page < 1 || page > Math.ceil(this.pagination.total / this.pagination.pageSize)) {
        return;
      }
      this.pagination.pageNum = page;
      this.fetchAdvertisements();
    },
    
    getPageNumbers() {
      const totalPages = Math.ceil(this.pagination.total / this.pagination.pageSize);
      const current = this.pagination.pageNum;
      const pages = [];
      
      // 显示当前页前后2页
      const start = Math.max(1, current - 2);
      const end = Math.min(totalPages, current + 2);
      
      for (let i = start; i <= end; i++) {
        pages.push(i);
      }
      
      return pages;
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '-';
      try {
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });
      } catch (error) {
        return dateString;
      }
    },

    // 格式化日期时间为后端期望的格式 (yyyy-MM-dd HH:mm:ss)
    formatDateTimeForBackend(dateTimeString) {
      if (!dateTimeString) return '';
      try {
        const date = new Date(dateTimeString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      } catch (error) {
        console.error('日期格式化错误:', error);
        return dateTimeString;
      }
    },

    // 格式化日期时间为前端datetime-local输入框格式 (yyyy-MM-ddTHH:mm)
    formatDateTimeForFrontend(dateTimeString) {
      if (!dateTimeString) return '';
      try {
        const date = new Date(dateTimeString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        
        return `${year}-${month}-${day}T${hours}:${minutes}`;
      } catch (error) {
        console.error('前端日期格式化错误:', error);
        return '';
      }
    },
    
    formatNumber(num) {
      return num ? num.toLocaleString('zh-CN') : '0';
    },
    
    getPositionText(position) {
      const positionMap = {
        banner: '横幅广告',
        sidebar: '侧边栏',
        popup: '弹窗广告',
        footer: '页脚广告',
        default: '未设置'
      };
      return positionMap[position] || position || '未设置';
    },
    
    getStatusText(status) {
      const statusMap = {
        active: '投放中',
        paused: '已暂停',
        expired: '已过期',
        draft: '草稿'
      };
      return statusMap[status] || status || '未知';
    },

    // 获取完整的图片URL
    getImageUrl(imageUrl) {
      if (!imageUrl) return '';
      
      // 如果已经是完整的URL，直接返回
      if (imageUrl.startsWith('http')) {
        return imageUrl;
      }
      
      // 如果是相对路径，拼接后端基础URL
      return this.backendBaseUrl + (imageUrl.startsWith('/') ? imageUrl : '/' + imageUrl);
    },
    editAd(ad) {
      console.log('编辑广告，原始数据:', ad);
      
      // 确保ID是数字
      this.editingId = parseInt(ad.id);
      console.log('设置editingId:', this.editingId);
      
      const imageUrl = ad.imageUrl || '';
      
      this.formData = {
        title: ad.title || '',
        imageUrl: imageUrl,
        targetUrl: ad.linkUrl || ad.targetUrl || '',
        position: ad.position || '',
        status: ad.status === 1 ? 'active' : (ad.status === 0 ? 'paused' : ad.status),
        startDate: this.formatDateTimeForFrontend(ad.startTime),
        endDate: this.formatDateTimeForFrontend(ad.endTime)
      };
      
      // 设置预览URL
      if (imageUrl) {
        if (imageUrl.startsWith('http')) {
          this.imageUrlForPreview = imageUrl;
        } else {
          this.imageUrlForPreview = this.backendBaseUrl + (imageUrl.startsWith('/') ? imageUrl : '/' + imageUrl);
        }
      } else {
        this.imageUrlForPreview = '';
      }
      
      this.showEditModal = true;
    },
    

    
    // 删除广告
    async deleteAd(id) {
      if (!confirm('确定要删除这个广告吗？')) {
        return;
      }
      
      try {
        const response = await axios.delete(`http://localhost:8083/api/v1/advertisements/delete/${id}`);
        
        console.log('删除广告响应:', response.data);
        
        if (response.data.code === 200 && response.data.ok && response.data.data === true) {
          alert('删除广告成功');
          this.fetchAdvertisements(); // 重新获取列表
        } else {
          alert('删除广告失败: ' + (response.data.msg || '未知错误'));
        }
      } catch (error) {
        console.error('删除广告出错:', error);
        if (error.response) {
          console.error('错误详情:', error.response.data);
          alert('删除广告失败: ' + (error.response.data.message || error.response.data.msg || '服务器错误'));
        } else {
          alert('删除广告失败: 网络连接错误');
        }
      }
    },
    
    // 切换广告状态
    async toggleStatus(ad) {
      try {
        const newStatus = ad.status === 'active' ? 0 : 1; // 0=禁用, 1=启用
        
        const adData = {
          id: ad.id,
          title: ad.title,
          imageUrl: ad.imageUrl,
          linkUrl: ad.linkUrl || ad.targetUrl,
          position: ad.position,
          status: newStatus,
          startTime: ad.startTime,
          endTime: ad.endTime,
          sortOrder: ad.sortOrder || 0,
          createdAt: ad.createdAt || '',
          updatedAt: ad.updatedAt || ''
        };

        const response = await axios.put(`http://localhost:8083/api/v1/advertisements/update/${ad.id}`, adData, {
          headers: {
            'Content-Type': 'application/json'
          }
        });

        console.log('切换广告状态响应:', response.data);

        if (response.data.code === 200 && response.data.ok && response.data.data === true) {
          alert(`广告状态已${newStatus === 1 ? '启用' : '禁用'}`);
          this.fetchAdvertisements(); // 重新获取列表
        } else {
          alert('切换状态失败: ' + (response.data.msg || '未知错误'));
        }
      } catch (error) {
        console.error('切换广告状态出错:', error);
        if (error.response) {
          console.error('错误详情:', error.response.data);
          alert('切换状态失败: ' + (error.response.data.message || error.response.data.msg || '服务器错误'));
        } else {
          alert('切换状态失败: 网络连接错误');
        }
      }
    },
    
    // 添加广告
    async addAd() {
      try {
        // 表单验证
        if (!this.formData.title.trim()) {
          alert('请输入广告标题');
          return;
        }
        if (!this.formData.imageUrl.trim()) {
          alert('请输入广告图片链接');
          return;
        }
        if (!this.formData.targetUrl.trim()) {
          alert('请输入目标链接');
          return;
        }
        if (!this.formData.position) {
          alert('请选择广告位置');
          return;
        }
        if (!this.formData.startDate) {
          alert('请选择开始时间');
          return;
        }
        if (!this.formData.endDate) {
          alert('请选择结束时间');
          return;
        }

        // 根据后端API要求的数据结构
        const adData = {
          id: 0,
          title: this.formData.title,
          imageUrl: this.formData.imageUrl,
          linkUrl: this.formData.targetUrl,
          position: this.formData.position,
          status: this.formData.status === 'active' ? 1 : 0,
          startTime: this.formatDateTimeForBackend(this.formData.startDate),
          endTime: this.formatDateTimeForBackend(this.formData.endDate),
          sortOrder: 0,
          createdAt: '',
          updatedAt: ''
        };

        const response = await axios.post('http://localhost:8083/api/v1/advertisements/add', adData, {
          headers: {
            'Content-Type': 'application/json'
          }
        });

        console.log('添加广告响应:', response.data);

        if (response.data.code === 200 && response.data.ok && response.data.data === true) {
          alert('添加广告成功');
          this.closeModal();
          this.fetchAdvertisements(); // 重新获取列表
        } else {
          alert('添加广告失败: ' + (response.data.msg || '未知错误'));
        }
      } catch (error) {
        console.error('添加广告出错:', error);
        if (error.response) {
          console.error('错误详情:', error.response.data);
          alert('添加广告失败: ' + (error.response.data.message || error.response.data.msg || '服务器错误'));
        } else {
          alert('添加广告失败: 网络连接错误');
        }
      }
    },

    // 更新广告
    async updateAd() {
      try {
        // 验证editingId
        if (!this.editingId || isNaN(this.editingId)) {
          alert('无效的广告ID，请重新选择要编辑的广告');
          console.error('无效的editingId:', this.editingId);
          return;
        }

        // 表单验证
        if (!this.formData.title.trim()) {
          alert('请输入广告标题');
          return;
        }
        if (!this.formData.imageUrl.trim()) {
          alert('请输入广告图片链接');
          return;
        }
        if (!this.formData.targetUrl.trim()) {
          alert('请输入目标链接');
          return;
        }
        if (!this.formData.position) {
          alert('请选择广告位置');
          return;
        }
        if (!this.formData.startDate) {
          alert('请选择开始时间');
          return;
        }
        if (!this.formData.endDate) {
          alert('请选择结束时间');
          return;
        }

        // 确保editingId是数字
        const adId = parseInt(this.editingId);
        console.log('准备更新广告，ID:', adId);

        // 根据后端API要求的数据结构
        const adData = {
          id: adId,
          title: this.formData.title,
          imageUrl: this.formData.imageUrl,
          linkUrl: this.formData.targetUrl,
          position: this.formData.position,
          status: this.formData.status === 'active' ? 1 : 0,
          startTime: this.formatDateTimeForBackend(this.formData.startDate),
          endTime: this.formatDateTimeForBackend(this.formData.endDate),
          sortOrder: 0,
          createdAt: '',
          updatedAt: ''
        };

        console.log('更新广告数据:', adData);
        console.log('API URL:', `http://localhost:8080/api/v1/advertisements/update/${adId}`);

        const response = await axios.put(`http://localhost:8080/api/v1/advertisements/update/${adId}`, adData, {
          headers: {
            'Content-Type': 'application/json'
          }
        });

        console.log('更新广告响应:', response.data);

        if (response.data.code === 200 && response.data.ok && response.data.data === true) {
          alert('更新广告成功');
          this.closeModal();
          this.fetchAdvertisements(); // 重新获取列表
        } else {
          alert('更新广告失败: ' + (response.data.msg || '未知错误'));
        }
      } catch (error) {
        console.error('更新广告出错:', error);
        if (error.response) {
          console.error('错误详情:', error.response.data);
          alert('更新广告失败: ' + (error.response.data.message || error.response.data.msg || '服务器错误'));
        } else {
          alert('更新广告失败: 网络连接错误');
        }
      }
    },

    saveAd() {
      if (this.showEditModal) {
        this.updateAd();
      } else {
        this.addAd();
      }
    },
    
    closeModal() {
      this.showAddModal = false;
      this.showEditModal = false;
      this.editingId = null;
      this.uploadProgress = 0;
      this.showManualInput = false;
      this.imageUrlForPreview = '';
      this.formData = {
        title: '',
        imageUrl: '',
        targetUrl: '',
        position: '',
        status: 'active',
        startDate: '',
        endDate: ''
      };
    },

    // 图片上传相关方法
    triggerFileInput() {
      this.$refs.fileInput.click();
    },

    handleFileSelect(event) {
      const file = event.target.files[0];
      if (file) {
        this.uploadImage(file);
      }
    },

    handleDrop(event) {
      const files = event.dataTransfer.files;
      if (files.length > 0) {
        this.uploadImage(files[0]);
      }
    },

    async uploadImage(file) {
      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件');
        return;
      }

      // 验证文件大小 (5MB)
      if (file.size > 5 * 1024 * 1024) {
        alert('图片文件大小不能超过5MB');
        return;
      }

      try {
        this.uploadProgress = 0;
        
        // 创建FormData对象
        const formData = new FormData();
        formData.append('file', file);

        // 上传图片
        const response = await axios.post('http://localhost:8080/api/v1/upload/image', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: (progressEvent) => {
            this.uploadProgress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          }
        });

        console.log('图片上传响应:', response.data);

        if (response.data.code === 200 && response.data.ok) {
          // 上传成功，设置图片URL
          let imagePath = response.data.data;
          
          // 确保路径格式正确
          if (imagePath && !imagePath.startsWith('http')) {
            // 如果是相对路径，确保以/开头
            if (!imagePath.startsWith('/')) {
              imagePath = '/' + imagePath;
            }
          }
          
          // 设置用于提交给后端的相对路径
          this.formData.imageUrl = imagePath;
          
          // 设置用于预览的完整URL
          this.imageUrlForPreview = this.backendBaseUrl + imagePath;
          
          this.uploadProgress = 100;
          
          // 延迟隐藏进度条
          setTimeout(() => {
            this.uploadProgress = 0;
          }, 1000);
          
          console.log('图片上传成功，相对路径:', imagePath);
          console.log('预览URL:', this.imageUrlForPreview);
          alert('图片上传成功');
        } else {
          alert('图片上传失败: ' + (response.data.msg || '未知错误'));
          this.uploadProgress = 0;
        }
      } catch (error) {
        console.error('图片上传出错:', error);
        this.uploadProgress = 0;
        
        if (error.response) {
          alert('图片上传失败: ' + (error.response.data.message || error.response.data.msg || '服务器错误'));
        } else if (error.request) {
          alert('图片上传失败: 网络连接错误');
        } else {
          alert('图片上传失败: 请求配置错误');
        }
      }
    },

    removeImage() {
      this.formData.imageUrl = '';
      this.imageUrlForPreview = ''; // 清空预览URL
      this.uploadProgress = 0;
      // 清空文件输入框
      if (this.$refs.fileInput) {
        this.$refs.fileInput.value = '';
      }
    }
  }
};
</script>

<style scoped>
.ad-management {
  padding: 0;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #2c3e50;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #6c757d;
  font-size: 14px;
}



.search-action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  padding: 20px 24px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  gap: 20px;
}

.search-box {
  display: flex;
  gap: 8px;
  align-items: center;
}

.search-input {
  padding: 12px 16px;
  border: 2px solid #e9ecef;
  border-radius: 10px;
  font-size: 14px;
  width: 300px;
  transition: all 0.3s ease;
  background: white;
}

.search-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.search-btn {
  padding: 12px 16px;
  border: none;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 10px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.search-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.create-btn {
  padding: 12px 24px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.filter-select {
  padding: 10px 16px;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  font-size: 14px;
  background: white;
}

.btn {
  display: inline-flex;
  align-items: center;
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.btn .icon {
  margin-right: 8px;
  font-size: 16px;
}

.ads-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.ad-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.ad-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.ad-card.inactive {
  opacity: 0.6;
}

.card-header {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.ad-preview {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  
  flex-shrink: 0;
}

.ad-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.ad-placeholder {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: 600;
}

.ad-info {
  flex: 1;
}

.ad-info h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #2c3e50;
  font-weight: 600;
}



.ad-meta {
  display: flex;
  gap: 8px;
}

.position-badge,
.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.position-badge.banner {
  background: #e3f2fd;
  color: #1976d2;
}

.position-badge.sidebar {
  background: #f3e5f5;
  color: #7b1fa2;
}

.position-badge.popup {
  background: #e8f5e8;
  color: #388e3c;
}

.position-badge.footer {
  background: #fff3e0;
  color: #f57c00;
}

.status-badge.active {
  background: #d4edda;
  color: #155724;
}

.status-badge.paused {
  background: #fff3cd;
  color: #856404;
}

.status-badge.expired {
  background: #f8d7da;
  color: #721c24;
}

.status-badge.draft {
  background: #e2e3e5;
  color: #383d41;
}

.card-actions {
  display: flex;
  gap: 8px;
  flex-direction: column;
}

.action-btn {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 6px;
  background: #f8f9fa;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  transition: all 0.3s ease;
}

.action-btn:hover {
  background: #e9ecef;
  transform: scale(1.1);
}

.action-btn.delete:hover {
  background: #f8d7da;
  color: #721c24;
}

.card-content {
  border-top: 1px solid #e9ecef;
  padding-top: 16px;
}

.ad-details {
  margin-bottom: 16px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.detail-row .label {
  font-size: 14px;
  color: #6c757d;
  font-weight: 500;
}

.detail-row .value {
  font-size: 14px;
  color: #2c3e50;
}

.detail-row .value.link {
  color: #667eea;
  text-decoration: none;
  max-width: 200px;
  
  text-overflow: ellipsis;
  white-space: nowrap;
}

.detail-row .value.link:hover {
  text-decoration: underline;
}

.ad-stats {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  display: block;
  font-size: 12px;
  color: #6c757d;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 700px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e9ecef;
}

.modal-header h3 {
  margin: 0;
  font-size: 20px;
  color: #2c3e50;
  font-weight: 600;
}

.close-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: #f8f9fa;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  color: #6c757d;
}

.close-btn:hover {
  background: #e9ecef;
}

.modal-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #2c3e50;
}

.form-input,
.form-textarea,
.form-select {
  width: 100%;
  padding: 10px 16px;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.form-input:focus,
.form-textarea:focus,
.form-select:focus {
  outline: none;
  border-color: #667eea;
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.ad-preview-container {
  border: 2px solid #e9ecef;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 200px;
  border-radius: 8px;
}

.preview-placeholder {
  height: 100px;
  border: 2px dashed #e9ecef;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6c757d;
  font-size: 14px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #e9ecef;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #5a6268;
}

/* 分页样式 */
.pagination-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 40px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.pagination-info {
  color: #6c757d;
  font-size: 14px;
  font-weight: 500;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.pagination-btn {
  padding: 10px 16px;
  border: 1px solid #e1e5e9;
  background: white;
  color: #495057;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-btn:hover:not(:disabled) {
  background: #f8f9fa;
  border-color: #667eea;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(102, 126, 234, 0.2);
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-numbers {
  display: flex;
  gap: 8px;
}

.page-number {
  padding: 10px 14px;
  border: 1px solid #e1e5e9;
  background: white;
  color: #495057;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 44px;
  text-align: center;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-number:hover {
  background: #f8f9fa;
  border-color: #667eea;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(102, 126, 234, 0.2);
}

.page-number.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-color: #667eea;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

@media (max-width: 1024px) {
  .ads-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .search-action-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
    padding: 16px;
  }
  
  .search-box {
    justify-content: center;
  }
  
  .search-input {
    width: 100%;
    max-width: 300px;
  }
  
  .create-btn {
    align-self: center;
    width: fit-content;
  }
  
  .ads-grid {
    grid-template-columns: 1fr;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .ad-stats {
    grid-template-columns: 1fr;
  }
  
  .pagination-wrapper {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .pagination-controls {
    justify-content: center;
    flex-wrap: wrap;
  }
}

/* 图片上传组件样式 */
.image-upload-container {
  border: 2px solid #e9ecef;
  border-radius: 12px;
  padding: 16px;
  background: #f8f9fa;
}

.image-preview {
  position: relative;
  display: inline-block;
  border-radius: 8px;
  
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.image-preview .preview-image {
  max-width: 100%;
  max-height: 200px;
  display: block;
  border-radius: 8px;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-preview:hover .image-overlay {
  opacity: 1;
}

.btn-remove {
  background: #dc3545;
  color: white;
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s ease;
}

.btn-remove:hover {
  background: #c82333;
  transform: scale(1.1);
}

.upload-area {
  border: 2px dashed #667eea;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
}

.upload-area:hover {
  border-color: #5a67d8;
  background: #f7fafc;
  transform: translateY(-2px);
}

.upload-content {
  color: #667eea;
}

.upload-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.upload-area p {
  margin: 8px 0;
  color: #4a5568;
  font-weight: 500;
}

.upload-hint {
  font-size: 12px !important;
  color: #718096 !important;
  font-weight: 400 !important;
}

.upload-progress {
  margin-top: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.progress-bar {
  flex: 1;
  height: 8px;
  background: #e2e8f0;
  border-radius: 4px;
  
}

.progress-fill {
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  transition: width 0.3s ease;
  border-radius: 4px;
}

.progress-text {
  font-size: 12px;
  color: #667eea;
  font-weight: 600;
  min-width: 40px;
}

.manual-input-toggle {
  margin-top: 16px;
  text-align: center;
}

.btn-link {
  background: none;
  border: none;
  color: #667eea;
  cursor: pointer;
  font-size: 14px;
  text-decoration: underline;
  transition: color 0.3s ease;
}

.btn-link:hover {
  color: #5a67d8;
}

.manual-input {
  margin-top: 12px;
}

.manual-input .form-input {
  background: white;
  border: 2px solid #e2e8f0;
}

.manual-input .form-input:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
</style>